package com.md.common.entity;

import com.md.common.exception.ApiErrorCode;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.builder.ToStringBuilder;

import java.io.Serializable;
import java.util.List;

/**
 * 功能描述：
 *
 * @author likaiwei
 * @version 1.0
 * @date 2018/6/21 0021 16:26
 * @since JDK 1.8
 */
public class AjaxResponse implements Serializable {
    private static final long serialVersionUID = 402814278293999469L;

    protected int code;//成功返回0
    protected String msg;//返回消息
    protected Object data = null;//返回结果

    public AjaxResponse() {
    }

    public AjaxResponse(int code, String msg, Object data) {
        super();
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public int getCode() {
        return code;
    }
    public void setCode(int code) {
        this.code = code;
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
    public Object getData() {
        return data;
    }
    public void setData(Object data) {
        this.data = data;
    }

    /**
     * 响应列表
     * @param list
     * @param total
     * @return
     */
    public static AjaxResponse success(List<?> list, Long total){
        return get(ApiErrorCode.SUCCESSFUL, new ApiErrorCode().getErrorMsg(ApiErrorCode.SUCCESSFUL),
                list, total);
    }

    /**
     * 响应对象
     * @param data
     * @return
     */
    public static AjaxResponse success(Object data){
        return get(ApiErrorCode.SUCCESSFUL, new ApiErrorCode().getErrorMsg(ApiErrorCode.SUCCESSFUL),
                data);
    }

    public static AjaxResponse success(){
        return get(ApiErrorCode.SUCCESSFUL, new ApiErrorCode().getErrorMsg(ApiErrorCode.SUCCESSFUL),
                null);
    }

    public static AjaxResponse success(String msg, Object data) {
        return get(ApiErrorCode.SUCCESSFUL, msg, data);
    }

    public static AjaxResponse error(int code, String msg, DataListReponse data){
        return get(code, msg, data);
    }

    public static AjaxResponse error(int code, String msg){
        return get(code, msg, null);
    }

    public static AjaxResponse error(int code, String msg, Object data){
        return get(code, msg, data);
    }
    public static AjaxResponse error(String msg) {
        return error(ApiErrorCode.SYSTEM_ERROR, msg);
    }

    private static AjaxResponse get(int code, String msg, Object data){
        return new AjaxResponse(code, msg, data);
    }

    private static AjaxResponse get(int code, String msg, List<?> list, Long total){
        DataListReponse dataListReponse = new DataListReponse();
        if(CollectionUtils.isNotEmpty(list)){
            dataListReponse.setList(list);
        }
        return new AjaxResponse(code, msg, dataListReponse);
    }

    @Override
    public String toString() {
        return ToStringBuilder.reflectionToString(this);
    }
}
